<script>
import gmForm from "@/view/components/gmForm.vue";
import gmDistrict from "@/view/components/gmDistrict.vue";
import studentMap from "@/view/components/studentMap.vue";
import studentAddRow from "@/view/components/studentAddRow.vue";
import classAddRow from "@/view/components/classAddRow.vue";
import treeCom from "@/view/traffic/studentCom/treeCom.vue";

export default {
  data() {
    return {
      treeData: [],
      listMode: true, //true=>列表模式 false=>地图模式
      tableForm: {},
      tableData: [],
      tablePage: {
        total: 0,
        current: 1,
        size: 10
      }
    }
  },
  components: {
    treeCom,
    gmForm: gmForm,
    gmDistrict: gmDistrict,
    studentMap: studentMap,
    studentAddRow: studentAddRow,
    classAddRow: classAddRow,
  },
  props: {
    tableColumns: Array,
    tableConfig: Object
  },
  methods: {
    getTableList(tag) {
      let params = null;
      if (tag === 'search') {
        params = {
          ...this.tableForm,
          current: this.tablePage.current,
          size: 10
        }
      } else {
        params = {
          current: this.tablePage.current,
          size: 10,
          districtCode: this.code
        }
        params[this.tableConfig['mainKey']] = this.tableConfig[this.tableConfig['mainKey']];
      }
      let url = !this.tableConfig.cancelPower ? 'findPageAuth' : 'findPage'
      this.$HttpService.get(`/${this.tableConfig.control}/${url}`, params).then(res => {
        this.tableData = res.records;
        this.tablePage.total = res.total;
        this.dicFilter();
        this.$forceUpdate()
      })
    },
    dicFilter() {
      let that = this;
      this.tableData.forEach(arrNode => {
        for (let val in arrNode) {
          doDic(val, arrNode)
        }
      })

      function doDic(k, n) {
        for (let i = 0; i < that.tableColumns.length; i++) {
          if (that.tableColumns[i].getValue) continue;
          if (that.tableColumns[i].id == k && that.tableColumns[i].dictObj) {
            n[k] = that.tableColumns[i].dictObj[n[k]] || n[k]
          }
        }
      }
    },
    toQuery() {
      this.getTableList('search');
    },
    resetQuery(needRefresh) {
      this.tableForm = {};
      this.tableColumns.forEach(x => {
        if (x.search) this.$set(this.tableForm, x.id, '')
        if (x.id === 'state') this.$set(this.tableForm, x.id, '01')
      })
      needRefresh && this.getTableList();
    },
    addLineData(row, active) {

      if (this.tableConfig.control === 't-class') this.$refs.classAdd.openDia(row, active) //学生的添加需要单独做弹窗，因为数据特殊
      else if (this.tableConfig.control === 't-student') this.$refs.gmStudentForm.openDia(row, active) //学生的添加需要单独做弹窗，因为数据特殊
      else this.$refs.gmForm.openDia(row, active, this.treeData, this.code)
    },
    handleEdit(row, active) {
      row.schoolGrade = row.schoolGrade + ''
      this.$refs.gmForm.openDia(row, active)
    },
    handleDelete(row) {
      this.$confirm(`确认要删除这条数据吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.$HttpService.del(`/${this.tableConfig.control}/delete-by-id/${row[this.tableConfig.mainKey]}`).then(() => {
          this.$message.success('删除成功！')
          this.getTableList();
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除！'
        })
      })
    },
    handleCurrentChange(page) {
      this.tablePage.current = page;
      this.getTableList();
    },
    clickSchoolTree(node){
      this.resetQuery(false);
      if (node.type == "districtCode") this.$set(this.tableForm, 'districtCode', node.districtCode)
      if (node.type == 'schoolCode')  this.$set(this.tableForm, 'schoolCode', node.schoolCode)
      if (node.type == 'gradeCode') this.$set(this.tableForm, 'gradeCode', node.id)
      if (node.type == 'classCode') this.$set(this.tableForm, 'classCode', node.classCode)
      this.getTableList('search')
    },
    clickTreeNode(code, treeData) {
      debugger
      this.code = code
      this.treeData = treeData
      this.$set(this.tableForm, 'districtCode', code)
      this.getTableList('search')
    },
    showClassPage(row) {
      this.$router.push({path: '/base/classList', params: {schoolCode: row.schoolCode}});
    },
    showImg(url) {
      alert(url)
    }
  },
  mounted() {
    this.tableColumns.forEach(x => {
      if (x.search) {
        this.$set(this.tableForm, x.id, '')
        if (x.id === 'state') this.$set(this.tableForm, x.id, '01')
      }
      if (x.required) {
        this.$HttpService.get(x.required).then((res) => {
          x.dictList = res.records ? res.records : res;
          x.dictObj = {};
          x.dictList.forEach(i => {
            if (x.props) {
              i['label'] = i[x.props.label]
              i['value'] = i[x.props.value]
            }
            x.dictObj[i.value] = i.label;
          })
        })
      }
    })
    this.getTableList();
  }
}
</script>

<template>
  <div class="table-out">
    <div class="table-form">
      <el-form ref="form" :inline="true" :model="tableForm" label-width="120px">
        <el-form-item v-for="x in tableColumns" :label="x.label" v-if="x.search">
          <el-input size="small" v-if="x.search && x.searchType === 'input'" :placeholder="`请输入${x.label}`"
                    v-model="tableForm[x.id]"></el-input>
          <el-select size="small" v-if="x.search && x.searchType === 'select'" v-model="tableForm[x.id]"
                     :placeholder="`请选择${x.label}`">
            <el-option v-for="item in x.dictList" :key="Math.random()" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-button class="filter-item" size="mini" type="success" icon="el-icon-search" @click="toQuery">搜索
        </el-button>
        <el-button class="filter-item" size="mini" type="warning" icon="el-icon-refresh-left"
                   @click="resetQuery(true)">重置
        </el-button>
        <el-button class="filter-item" size="mini" type="primary" icon="el-icon-plus"
                   @click="addLineData(tableColumns,'add')">新增数据
        </el-button>
        <el-button class="filter-item" size="mini" type="info" icon="el-icon-share"
                   v-if="tableConfig.control === 't-student'">批量导入
        </el-button>
      </el-form>
      <div class="exchange" v-if="tableConfig.control === '/api/tStudent'">
        <el-switch
            style="display: block"
            v-model="listMode"
            active-color="#13ce66"
            inactive-color="#1890ff"
            active-text="列表模式"
            inactive-text="地图模式">
        </el-switch>

      </div>
    </div>
    <div class="page-center">
      <div class="dist-com" v-if="tableConfig.needDist">
        <tree-com v-if="tableConfig.control == 't-class'" @clickNode="clickSchoolTree"></tree-com>
        <gm-district v-else @clickNode="clickTreeNode"></gm-district>
      </div>
      <div class="table-com" v-if="!listMode && tableConfig.control === '/api/tStudent'"
           :class="tableConfig.needDist?'no-full':'full'">
        <student-map></student-map>
        <el-pagination
            :page-size="tablePage.size"
            :pager-count="tablePage.current"
            layout="prev, pager, next"
            background
            @current-change="handleCurrentChange"
            :total="tablePage.total">
        </el-pagination>
      </div>
      <div class="table-com" v-else :class="tableConfig.needDist?'no-full':'full'">
        <el-table border :data="tableData" stripe style="width: 100%" type="flex" justify="center" align="middle">
          <el-table-column align="center" v-for="x in tableColumns" :prop="x.id" :label="x.label" :width="x.width"
                           v-if="!x.hide">
            <template slot-scope="scope">
              <span v-if="x.getValue">
                <el-image v-if="x.searchType === 'upload'" style="width: 60px; height: 60px"
                          :preview-src-list="[x.getValue(scope.row[x.id])]"
                          :src="x.getValue(scope.row[x.id])"></el-image>
                <span v-else>{{ x.getValue(scope.row[x.id]) }}</span>
              </span>
              <span v-else v-html="scope.row[x.id]"></span>
            </template>
          </el-table-column>
          <el-table-column width="200px" align="center" label="操作">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row,'update')">编辑
              </el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="page-out">
          <el-pagination
              background
              :page-size="tablePage.size"
              :page-count="tablePage.current"
              layout="prev, pager, next"
              @current-change="handleCurrentChange"
              :total="tablePage.total">
          </el-pagination>
        </div>
      </div>
    </div>
    <gm-form ref="gmForm" @onSuccess="getTableList" :table-config="tableConfig"
             :table-columns="tableColumns"></gm-form>
    <studentAddRow ref="gmStudentForm" @onSuccess="getTableList" :table-config="tableConfig"
                   :table-columns="tableColumns"></studentAddRow>
    <class-add-row @success="getTableList" ref="classAdd"></class-add-row>
  </div>
</template>

<style scoped>
.table-form {
  width: 98%;
  padding: 20px;
  border-radius: 20px;
  background-color: white;
  margin: 0 auto;
  box-shadow: 3px 3px 3px 2px #e8e8e8;
  position: relative;
  background-image: url("../../assets/images/searbg.jpg");
  background-repeat: no-repeat;
  background-position: right -20px;
  background-size: 14%;

  .exchange {

    position: absolute;
    right: 10px;
    bottom: 10px;

  }

  .filter-item {
    position: relative;
    top: 5px
  }
}

.page-center {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin: 20px auto;

  .no-full {
    width: calc(100% - 340px);
  }

  .full {
    width: 100% !important;
  }

  .dist-com {
    width: 250px;
    padding: 20px;
    min-height: 40vh;
    background-color: #ffffff;
    border-radius: 20px;
    box-shadow: 3px 3px 3px 2px #e8e8e8;
  }

  .table-com {
    padding: 20px;
    border-radius: 20px;
    background-color: white;
    box-shadow: 3px 3px 3px 2px #e8e8e8;
    width: calc(100% - 350px);

    .page-out {
      padding-top: 20px;
      text-align: center;
    }
  }
}
</style>
